import { reactive, ref } from "vue";
import { deleteArticleAPI, getArticleAPI, getArticleOfKeywordAPI } from "@/api/creation.ts";
import { ElMessage } from "element-plus";

export default function useArticle() {

  const dialogVisible = ref(false)
  const dialog = ref()
  const articleList = ref()
  const keyword = ref()
  const total = ref(0)
  const params = reactive({
    limit: 6,
    page: 1
  })

  // 获取文章列表
  const getArticleList = async () => {
    const res = await getArticleAPI(params)
    articleList.value = res.data.articles
    total.value = res.data.total
  }

// 关键字搜索
  const getArticleOfKeyword = async () => {
    const res = await getArticleOfKeywordAPI(keyword.value)
    articleList.value = res.data
    dialogVisible.value = true
    keyword.value = ''
  }

  // 删除文章
  const deleteArticle = async (id: string) => {
    const res: any = await deleteArticleAPI(id)
    if (res.code === 0) {
      ElMessage({
        type: 'success',
        message: res.message
      })
    }
    await getArticleList()
  }

  // 编辑文章
  const EditArticle = (row: any) => {
    dialog.value.init(row)
  }

  return {
    keyword,
    dialog,
    getArticleOfKeyword,
    articleList,
    EditArticle,
    deleteArticle,
    getArticleList
  }
}
